package com.example.bankend.service.impl;

import com.example.bankend.entity.Card;
import com.example.bankend.entity.Saving;
import com.example.bankend.entity.Trade;
import com.example.bankend.entity.User;
import com.example.bankend.mapper.CardMapper;
import com.example.bankend.mapper.SavingMapper;
import com.example.bankend.mapper.TradeMapper;
import com.example.bankend.mapper.UserMapper;
import com.example.bankend.service.CardService;
import com.example.bankend.service.TradeService;
import com.example.bankend.service.UserService;
import com.example.bankend.util.Random;
import com.example.bankend.util.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author luolinila
 * @date 2025/6/16 21:33
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TradeMapper tradeMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private SavingMapper savingMapper;

    @Override
    public int sendCaptcha(String phone) {
        try {
            String captcha = Random.randomCaptcha();
            Sample.sendSms(phone, captcha);
            redisTemplate.opsForValue().set("captcha_" + phone, captcha, 3, TimeUnit.MINUTES);
            return 200;
        } catch (Exception e) {
            System.out.println(e);
            return -1;
        }
    }

    @Override
    public Long create(Long adminID, String adminName, String adminPass, String cunstomerName, String PID, String telephone, String password) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User tempuser = userMapper.selectByPID(PID);
            System.out.println(tempuser);
            if (tempuser != null) {
                if ("0".equals(tempuser.getIsDelete())) {
                    return -1L;
                }else {
                    recoverUserByID(tempuser.getCustomerID());
                    userMapper.updateUserbase(telephone, tempuser.getCustomerID(), password, "未填写");
                    createCardAuto(tempuser.getCustomerID());
                    return tempuser.getCustomerID();
                }
            }
            List<Long> customerIDList = getAllCustomerID();
            System.out.println(customerIDList);
            Long newCustomerID = Random.randomLong();
            while (customerIDList.contains(newCustomerID)) {
                newCustomerID = Random.randomLong();
            }
            System.out.println(newCustomerID);
            User newUser = new User(newCustomerID, cunstomerName, PID, telephone, "未填写", password, "0");
            userMapper.insertUser(newUser);
            createCardAuto(newCustomerID);
            customerIDList.add(newCustomerID);
            redisTemplate.opsForValue().set("allCustomerID", customerIDList, 1, TimeUnit.HOURS);
            return newCustomerID;
        } catch (Exception e) {
            System.out.println(e);
            System.out.println(e.getMessage());
            return (long) -1;
        }
    }

    @Override
    public User getUserByCunstomerID(Long cunstomerID) {
        try {
            User user = userMapper.selectByCunstomerID(cunstomerID);
            if (user == null || "1".equals(user.getIsDelete())) {
                return null;
            }
            return user;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    @Override
    public Long loginByPIDAndPass(String PID, String pass) {
        try {
            User user = getUserByCunstomerPID(PID);
            if (user == null) {
                return -1L;
            }
            if (!pass.equals(user.getPass())) {
                return -1L;
            }
            return user.getCustomerID();
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }


    @Override
    public Long deleteUser(Long adminID, String adminName, String adminPass, Long customerID) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User user = getUserByCunstomerID(customerID);
            if (user == null) {
                return 10003L;
            }
            List<String> cardIDList = userMapper.getCardIDByCustomerID(user.getCustomerID());
            for (String cardID : cardIDList) {
                tradeMapper.deleteallByCardID(cardID);
                cardMapper.deleteCard(cardID);
            }
            userMapper.deleteUser(user.getCustomerID());
            return 200L;
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public User getAdmin() {
        try {
            User admin = userMapper.selectAdmin();
            System.out.println(admin);
            return admin;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public Long updateUser(Long adminID, String adminName, String adminPass, Long customerID, String pass, String telephone, String address) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User user = getUserByCunstomerID(customerID);
            if (user == null) {
                return 10001L;
            }
            userMapper.updateUserbase(telephone, user.getCustomerID(), pass, address);
            return user.getCustomerID();
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public Long selectByID(Long adminID, String adminName, String adminPass, Long customerID) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User user = getUserByCunstomerID(customerID);
            if (user == null) {
                return 10001L;
            }
            return user.getCustomerID();
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public List<User> selectLikeByName(Long adminID, String adminName, String adminPass, String customerName) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return null;
            }
            List<User> res = userMapper.selectLikeByName(customerName);
            return res;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    @Override
    public Long selectByPID(Long adminID, String adminName, String adminPass, String pid) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User user = userMapper.selectByPID(pid);
            if (user == null || "1".equals(user.getIsDelete())) {
                return 10001L;
            }
            return user.getCustomerID();
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public Long selectByPhone(Long adminID, String adminName, String adminPass, String telephone) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return -1L;
            }
            User user = userMapper.selectByTelephone(telephone);
            if (user == null || "1".equals(user.getIsDelete())) {
                return 10001L;
            }
            return user.getCustomerID();
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public Long recoverUserByID(Long customerID) {
        try {
            User user = userMapper.selectByCunstomerID(customerID);
            if (user == null) {
                return -1L;
            }
            userMapper.recoverUserByID(customerID);
            return customerID;
        } catch (Exception e) {
            System.out.println(e);
            return -1L;
        }
    }

    @Override
    public List<User> selectAll(Long adminID, String adminName, String adminPass) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return null;
            }
            return userMapper.selectAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User getUserByCunstomerPID(String PID) {
        try {
            User user = userMapper.selectByPID(PID);
            if (user == null || "1".equals(user.getIsDelete())) {
                return null;
            }
            return user;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    @Override
    public User loginAdmin(Long adminID, String adminName, String adminPass) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return null;
            }
            return admin;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }



    @Override
    public List<User> getAllUser(Long adminID, String adminName, String adminPass) {
        try {
            User admin = getAdmin();
            if (!adminName.equals(admin.getCustomerName()) || adminID.compareTo(admin.getCustomerID()) != 0 || !adminPass.equals(admin.getPass())) {
                return null;
            }
            return userMapper.selectAll();
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    @Override
    public List<Long> getAllCustomerID() {
        List<Long> list = (List<Long>) redisTemplate.opsForValue().get("allCustomerID");
        if (list == null) {
            list = userMapper.selectAllCustomerID();
        }
        redisTemplate.opsForValue().set("allCustomerID", list, 1, TimeUnit.HOURS);
        return list;
    }

    @Override
    public int createCardAuto(Long CustomerID) {
        try {
            User user =  userMapper.selectByCunstomerID(CustomerID);
            if(user == null) {
                return -1;
            }
            Card card = new Card();
            List<String> list = selectAllCardID();
            String newCardID = Random.randomCardNumber();
            while (list.contains(newCardID)) {
                newCardID = Random.randomCardNumber();
            }
            card.setCardID(newCardID);
            card.setCurID("RMB");
            card.setOpenDate(new Timestamp(System.currentTimeMillis()));
            card.setOpenMoney(new BigDecimal(0));
            card.setBalance(new BigDecimal(0));
            card.setPass("888888");
            card.setIsReportLoss("0");
            Saving saving = savingMapper.selectSavingByName("活期");
            card.setSavingID(saving.getSavingID());
            card.setCustomerID(CustomerID);
            card.setIsDelete("0");
            cardMapper.insertCard(card);
            list.add(newCardID);
            redisTemplate.opsForValue().set("allCardId", list, 1, TimeUnit.HOURS);
            return 200;
        } catch (Exception e) {
            System.out.println(e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> selectAllCardID() {
        List<String> list = (List<String>) redisTemplate.opsForValue().get("allCardId");
        if (list == null) {
            list = cardMapper.selectAllCardID();
        }
        redisTemplate.opsForValue().set("allCardId", list, 1, TimeUnit.HOURS);
        return list;
    }
}
